<template>
  <div id="wrapper" >


<!--    顶栏-->
    <div  class="editorheader" >
  <span style="margin-left: 1400px; cursor: pointer" @click="GoToPreview">预览</span>
    </div>


    <div class="container" >
      <div class="container_inner">

<!--    左侧题型选择与大纲    -->
      <div class="editorleft" >
        <div class="AddQuestionAndShowMenu">

          <el-tabs v-model="activeName" type="border-card" :stretch="true" style="position: relative; height: 100%" >
            <el-tab-pane label="题目组件" name="questions" style="color:black;">
              <draggable :value="typelist"
                         :group='{name:"site",put:false,pull:"clone"}'
                         :sort="false"
                         :fallbackTolerance="90"
                         draggable=".QuestionType"
                         :clone="onClone"
                         filter=".QuestionTypeTitle"
                         animation="0"
                         chosenClass="TypeChosen"
                         forceFallback="true"
              >
                <div class="QuestionTypeTitle">报名问卷</div>

                <el-popover placement="right" width="400" trigger="hover"  ref="singlechoice" :close-delay= "0" :open-delay="200">
                        <preview-single-choice></preview-single-choice>
                </el-popover>

                <div class="QuestionType" v-popover:singlechoice @click="clickToAdd('S')" >单选题</div>

                 <el-popover placement="right" width="400" trigger="hover"  ref="mulchoice" :close-delay= "0" :open-delay="200">
                        <preview-mutiple-choive></preview-mutiple-choive>
                </el-popover>

                <div class="QuestionType" v-popover:mulchoice @click="clickToAdd('M')">多选题</div>

                <el-popover placement="right" width="400" trigger="hover"  ref="fill" :close-delay= "0" :open-delay="200">
                  <preview-fill></preview-fill>
                </el-popover>

                <div class="QuestionType" v-popover:fill @click="clickToAdd('F')">填空题</div>

                <el-popover placement="right" width="400" trigger="hover"  ref="name" :close-delay= "0" :open-delay="200">
                  <preview-name></preview-name>
                </el-popover>

                <div class="QuestionType" v-popover:name @click="clickToAdd('Name')">姓名</div>

                <el-popover placement="right" width="400" trigger="hover"  ref="id" :close-delay= "0" :open-delay="200">
                  <preview-i-d></preview-i-d>
                </el-popover>

                <div class="QuestionType" v-popover:id @click="clickToAdd('ID')">手机号</div>


              
              </draggable>


            </el-tab-pane>
            <el-tab-pane label="问卷大纲" name="menu">
                <draggable v-model="arr"  :sort="true"
                           :group='{name:"Menu",put:false,pull:false}'
                           ghostClass="QuesGhost" chosenClass="QuesChosen"
                           forceFallback="true"
                           animation="100"
                ><div v-for="(item,index) in arr"
                       @click="clickToEdit(item.id,item)"
                       class="queMenuItem"
                       :style="queMenuItemActive(item.id)"
                       :key="item.id">
                    <span>{{index+1}}</span><span>{{item.title}}</span>
                  </div>
                </draggable>

            </el-tab-pane>
          </el-tabs>

        </div>
      </div>

<!--      编辑问卷块的样式-->
      <div class="editormainshow"  >
          <div  class="scrollbar" id="style-1">
              <div class="thepaper"  ><!--问卷内容-->
                <div class="thePaperTitleAndRemark" @click="clickToEdit(-1,null)">
                  <div class="theQnTitle">{{title}}</div>
                </div>

                <div class="thePaperQuestions">
                  <draggable :list="arr"
                             :group='{name:"site",put:true}'
                             :sort="true"
                             ghostClass="QuesGhost" chosenClass="QuesChosen"
                             forceFallback="true"
                             :animation="250"
                             :fallbackTolerance="90"
                             :delay="50"
                              @add="addadd($event)"
                  >
                    <div v-for="(item,index) in arr"
                         @click="clickToEdit(item.id,item)"
                         :key="item.id">
                      <el-button v-show="idBeingEditing==item.id"   @click="DeleteItem(index,item.id)"
                                 circle  icon="el-icon-delete" type="text"
                                 style="float:right;position: relative; z-index:999;color:red"
                      ></el-button>
                      <el-button v-show="idBeingEditing==item.id"   @click="CopyItem(index,item.id,item)"
                                 circle  icon="el-icon-document-copy" type="text"
                                 style="float:right;position: relative; top:40px;left:40px;z-index:999;color:blue"
                      ></el-button>



                      <div>

                         <template  v-if="item.type=='S'">
                           <e-single-choice :item="item" :autoId="showId" :num="index"
                                    :tt="qwq" :ifIsEditing="idBeingEditing==item.id"></e-single-choice>
                         </template>
                      <template v-else-if="item.type=='M'">
                        <e-mul-choice :item="item" :autoId="showId" :num="index"
                                         :tt="qwq" :ifIsEditing="idBeingEditing==item.id"></e-mul-choice>
                      </template>
                        <template v-else-if="item.type=='F'" >
                          <e-single-tiankong :item="item" :autoId="showId" :num="index"
                                             :tt="qwq" :ifIsEditing="idBeingEditing==item.id"></e-single-tiankong>
                        </template>

                      </div>

                    </div>
                    
                  </draggable>
                </div>

                <div class="thePaperTail">
                  <el-button type="primary" disabled>提交</el-button>
                </div>

                <div style="clear:both;"></div>


              </div>
        </div>


      </div >
        <!--     右侧问卷设置、题目编辑窗口-->
        <div class="editorright">
          <div class="SetQuestionAndThePaper" >
            <template v-if="rightshowTitle">
              <e-set-qn @hehe="lala"
                        :showid="showId"
                        :title="title"
                        :ifsetddl="ifSetDDL"
                        :tt="qwq"
                        :ddl="DDL"
                        @setshowid="setshowid"
                        @changetitle="ChangeTitle"
                        @setifddl="SetIfDDL"
                        @setddl="SetDDL"
              ></e-set-qn>
            </template>


            <template v-if="rightshowQues">
              <enroll-choice-edit @hehe="lala"
                             :item="itemBeingEditing"
              ></enroll-choice-edit>
            </template>

          </div>
          <el-button style="width: 420px;height: 40px;margin:4px 0px 0px 4px; font-size: 18px"  type="primary"
                  @click="SaveWholeQn"
          >保存</el-button>

        </div>
    </div>
    </div>


  </div>
</template>

<script>
import draggable from 'vuedraggable';
import ESingleChoice from "../../../components/Exam/ESingleChoice";
import ESingleTiankong from "../../../components/Exam/ESingleTiankong";
import EMulChoice from "../../../components/Exam/EMulChoice";
import PreviewFill from '@/components/Preview/PreviewFill';
import PreviewName from '@/components/Preview/PreviewName';
import PreviewID from '@/components/Preview/PreviewID';
import ESetQn from "../../../components/Exam/ESetQn";
import EnrollChoiceEdit from '@/components/Enroll/EnrollChoiceEdit'
import PreviewMutipleChoive from '@/components/Preview/PreviewMutipleChoive'
import PreviewSingleChoice from '@/components/Preview/PreviewSingleChoice'
//import ESingleTiankong from "../../../components/Exam/ESingleTiankong";
import {
  GetApply,
  questionCreateSelection,
  questionCreateOption,
  confirmQuestionnaireOrder,
  questionnaireChangeQuestionnaireTitle,
  questionnaireSetIsOrder,
  questionDelQuestion,
  questionCopyQuestion,
  questionEditQuestion,
  questionCreateNonSelection,
  questionnaireSetDeadline
} from "../../../api";
export default{
  name:'ExamEdit',
  components:{
    draggable,
    ESingleChoice,ESetQn,EnrollChoiceEdit ,EMulChoice,PreviewMutipleChoive,PreviewSingleChoice,
    PreviewFill,
    PreviewName,
    PreviewID,ESingleTiankong
  },
  data(){
    return{
      qwq:0,
      questionnaire_id:-1,
      theWindowHeight:800,
      idBeingEditing:-1,
      typeBeingAdding:-1,
      itemBeingEditing:null,
      activeName: 'questions',
      arr:[],
      showId:true,
      title:'',
      ifSetDDL:false,
      DDL:JSON.stringify(new Date(2021,7,30,20,40)),
      typelist:[
        {
          id:0,
          val:'小标题'
        },
        {
          id:0,
          val:'小标题'
        },
        {
          key:false,
          id:1,
          val:'S',//单选
        },
        {
          id:0,
          val:'小标题'
        },
        {
          key:false,
          id:2,
          val:'M'//多选
        },
        {
          id:0,
          val:'小标题'
        },
        {
          key:false,
          id:3,
          val:'F'//填空
        },
        {
          id:0,
          val:'小标题'
        },
        {
          key:false,
          id:4,
          val:'Name'//姓名
        },
        {
          id:0,
          val:'小标题'
        },
        {
          key:false,
          id:5,
          val:'ID'//手机号
        },
      ],
      tempSingleChoice:{
        title:'我是一道单选题',
        type:'S',
        optional:false,
        remark:'',
        option:[
          {
            description:'我是第一个选项',
            id:-2,
          },
          {
            description:'我是第二个选项',
            id:-3,
          }
        ]
      },
      tempMulChoice:{
        title:'我是一道多选题',
        type:'M',
        optional:false,
        remark:'',
        option:[
          {
            description:'我是第一个选项',
            id:-2,
          },
          {
            description:'我是第二个选项',
            id:-3,
          }
        ]
      },
      tempTk:{
        title:'我是一道填空题',
        type:'F',
        optional:false,
        remark:'',
      },
      tempName:{
        title:'姓名',
        type:'F',
        optional:true,
        remark:'',
      },
      tempTel:{
        title:'手机号',
        type:'F',
        optional:true,
        remark:'',
      },
    }
  },
  mounted() {
    this.questionnaire_id=JSON.parse(this.$UrlEncode.decode(this.$route.query.questionnaireId))/1234;
    this.setCssHeightForTheWindow();
    this.getInfo();//获取问卷数据
    console.log(this.arr)
    this.$forceUpdate();
  },
  computed:{
    queMenuItemActive(){
      return function (myId){
        if(this.idBeingEditing==myId){
          return "opacity:1";
        }else return "";
      }
    },

    rightshowTitle:function (){
      if(this.idBeingEditing===-1)return true;else return false;
    },
    rightshowQues:function (){
      if(this.idBeingEditing===-1){return false;} else return true;
    },
    // 监听窗口高度改变编辑外框的大小，使得最外层窗口没有滚动条——计算属性，改:style样式

    getEditBoxRightHeight:function (){
      var hhh=this.theWindowHeight-55;
      if(hhh>0){
        return "height:"+hhh+"px";
      }else return "";
    }
  },
  methods:{
    // 修改问卷标题
    ChangeTitle:function (e){
      this.title=e;
    },
    // 删除题目
    DeleteItem:function (indexx,itemid){
      console.log(this.arr);
      console.log(indexx,itemid);
      questionDelQuestion(this.$store.state.uid,this.questionnaire_id,itemid).then(res=>{
        if(res.error_code==0){
          this.arr.splice(indexx,1);
          console.log("删除成功",itemid);
          console.log(this.arr);
        }else{
          console.log(res);
        }
      })
    },
    // 复制题目
    CopyItem:function (indexx,itemid,ite){
      questionCopyQuestion(this.$store.state.uid,itemid).then(res=>{
        if(res.error_code==0){
          var copyite=JSON.parse(JSON.stringify(ite));
          copyite.id=res.question_id;
          this.$set(copyite,'isEditing',false);
          this.arr.splice(indexx+1,0,copyite);
          console.log("复制成功",itemid);
          console.log(this.arr);
        }
      })
    },
    // 保存问卷
    async ReqToSave(){
      var uid=this.$store.state.uid;
      var Qlist=[];
      var x=1;
      for(var i in this.arr){
        Qlist.push(this.arr[i].id);
        if(this.arr[i].type=='S'||this.arr[i].type=='M'){
          questionEditQuestion(uid,this.arr[i].id,this.arr[i].title,this.arr[i].optional,this.arr[i].remark,this.arr[i].option).then(res=>{
            console.log(x);
            if(res.error_code==0){x=x+1;}else{console.log(res);}
          });
        }else{
          questionEditQuestion(uid,this.arr[i].id,this.arr[i].title,this.arr[i].optional,this.arr[i].remark,[]).then(res2=>{
            console.log(x);
            if(res2.error_code==0){x=x+1;}else{console.log(res2);}
          });
        }
      }
      confirmQuestionnaireOrder(uid,this.questionnaire_id,Qlist).then(res3=>{if(res3.error_code==0){console.log("成功上传题目顺序",Qlist)}else console.log(res3);})
      questionnaireChangeQuestionnaireTitle(uid,this.questionnaire_id,this.title).then(res4=>{if(res4.error_code==0){console.log("成功上传问卷标题")}else console.log(res4); })
      questionnaireSetIsOrder(uid,this.questionnaire_id,this.showId).then(res5=>{if(res5.error_code==0){console.log("成功确认是否显示系统题号",this.showId)}else console.log(res5);})
      return x;
    },
    SaveWholeQn:function(){
      const loading=this.$loading({
        lock:true,
        text:'正在保存',
        spinner:'el-icon-loading',
        background:'rgba(0,0,0,0.7)'
      });
      this.ReqToSave().then(res => {
        console.log("QQQ",res);
        console.log(this.arr);

        loading.close();
        this.$notify({
          title: '保存成功',
          type:'success',
          duration:1000,
          position: 'bottom-left'
        });

      })
    },

    // 强制prop了对象的子组件刷新的trick
    lala:function(){this.qwq++;},

    // 从左侧拖出触发的事件
    onClone:function (e){this.typeBeingAdding=e.val;},
    addadd:function (e){
      switch (this.typeBeingAdding){
        case 'S':this.itemBeingEditing=JSON.parse(JSON.stringify(this.tempSingleChoice));this.addSelection();break;
        case 'M':this.itemBeingEditing=JSON.parse(JSON.stringify(this.tempMulChoice)); this.addSelection();break;
        case 'F':this.itemBeingEditing=JSON.parse(JSON.stringify(this.tempTk));this.addNonSelection();break;
        case 'Name':this.itemBeingEditing=JSON.parse(JSON.stringify(this.tempName));this.addNonSelection();break;
        case 'ID':this.itemBeingEditing=JSON.parse(JSON.stringify(this.tempTel));this.addNonSelection();break;
      }
      this.arr.splice(e.newIndex,0,this.itemBeingEditing);
    },
    clickToAdd:function (x){
      switch (x){
        case 'S':this.itemBeingEditing=JSON.parse(JSON.stringify(this.tempSingleChoice));this.addSelection();break;
        case 'M':this.itemBeingEditing=JSON.parse(JSON.stringify(this.tempMulChoice)); this.addSelection();break;
        case 'F':this.itemBeingEditing=JSON.parse(JSON.stringify(this.tempTk));this.addNonSelection();break;
        case 'Name':this.itemBeingEditing=JSON.parse(JSON.stringify(this.tempName));this.addNonSelection();break;
        case 'ID':this.itemBeingEditing=JSON.parse(JSON.stringify(this.tempTel));this.addNonSelection();break;
      }
      this.arr.push(this.itemBeingEditing);
    },

    // 添加选择题
    addSelection:function (){
      console.log(this.$store.state.uid,this.itemBeingEditing.title,this.itemBeingEditing.type,this.itemBeingEditing.optional,this.itemBeingEditing.remark,this.questionnaire_id);
      questionCreateSelection(this.$store.state.uid,this.itemBeingEditing.title,this.itemBeingEditing.type,this.itemBeingEditing.optional,this.itemBeingEditing.remark,this.questionnaire_id)
          .then(res=>{
            console.log(res);
            if(res.error_code==0) {
              this.itemBeingEditing.id = res.question_id;
              this.idBeingEditing = res.question_id;

              questionCreateOption(this.$store.state.uid, res.question_id, 0, this.itemBeingEditing.option[0].description, '')
                  .then(res1 => {
                    if (res1.error_code == 0) {
                      this.itemBeingEditing.option[0].id = res1.option_id;
                      questionCreateOption(this.$store.state.uid, res.question_id, 1, this.itemBeingEditing.option[1].description, '')
                          .then(res2 => { console.log(res2);  if (res2.error_code == 0) {this.itemBeingEditing.option[1].id = res2.option_id;  }})
                    }}).catch(e=>{console.log(e)})
            }else{console.log(res);}}).catch(e=>{console.log(e)})
    },

    // 添加非选择题
    addNonSelection:function (){//还需要判断当前是否有未保存的题目，还没判断
      questionCreateNonSelection(this.$store.state.uid,this.itemBeingEditing.title,this.itemBeingEditing.type,this.itemBeingEditing.optional,this.itemBeingEditing.remark,this.questionnaire_id)
          .then(res=>{if(res.error_code==0){this.itemBeingEditing.id=res.question_id;this.idBeingEditing=res.question_id;
          }else{console.log(res);}}).catch(e=>{console.log(e);})
    },

    // 点击题目进行编辑
    clickToEdit(editType,item){
      this.idBeingEditing=editType;
      if(this.itemBeingEditing!=-1){
        this.itemBeingEditing=item;
      }
    },

    // 获取全部已有题目
    getInfo:function (){
      GetApply(this.questionnaire_id).then(res=>{
        if(res.error_code==0){
            console.log(res)
          this.arr=res.question_list
          this.title=res.questionnaire_title;
          this.showId=res.is_order
          this.qwq++;
        }else{
          switch (res.error_code){
            case 4:alert("当前问卷为空");break;
          }
        }
      });
    },


    // 监听窗口高度改变编辑外框的大小，使得最外层窗口没有滚动条——监听，改值
    setCssHeightForTheWindow:function(){
      this.theWindowHeight=document.body.offsetHeight;
      console.log(this.theWindowHeight,document.body.offsetWidth);
    },
    /*拖拽功能*/
    // 设置问卷
    setshowid:function (v){
      this.showId=v;
    },
    SetIfDDL:function (v){
      this.ifSetDDL=v;
    },
    SetDDL:function (v){
      this.DDL=v;
      console.log(this.DDL);
      // v=JSON.stringify(v);
      // console.log("vv",v);
      questionnaireSetDeadline(this.$store.state.uid,this.questionnaire_id,v).then(res=>{
        if(res.error_code==0){
          this.$notify({
            title:'成功设定问卷截止时间',
            message:'问卷截止时间为'+this.DDL,
            type:'success',
            position:"bottom-left"
          })
        }else{
          switch (res.error_code){
            case 2:this.notetwo();break;
            case 3:this.notethree();break;
            case 4:this.notefour();break;
          }
        }
      })
    },
    // error_code=2（用户不存在）的提醒
    notetwo(){
      this.$notify.error({
        message:'用户不存在',
      })
    },
    notethree(){
      this.$notify.error({
        message:'问卷不合法',
      })
    },
    notefour(){
      this.$notify.error({
        message:'时间不合法',
      })
    }

  }
};

</script>

<style scoped>


/*最外层*/
#wrapper {
  background-color: #d8e2fc;
  height: 100%;
}
/*顶部栏的样式*/
.editorheader{
  background-color: #738cc2;
  color:white;
  line-height:40px;
}

.container{
  padding:4px 0 0 0;
}
.container_inner{
  width: 1510px;
  margin:0px auto;
  display: flex;
  justify-content: center;
}


/*左侧题型选择与大纲*/

.editorleft{
  /*width: 370px;*/
  height: 707px;
  width: 365px;
  margin-top: 5px;
}
.AddQuestionAndShowMenu{
  background-color: white;
  /*background-color: #cad1e3;*/
  width: 296px;
  height: 707px;
  margin: 0 4px 4px auto;
  box-shadow: 0px 1px 2px #a9aaa9
}
.QuestionTypeTitle{
  position: relative;
  width: 100%;
  font-weight: bold;
  font-size: 16px;
  text-align: left;
  height: 30px;
  margin-top:15px;
  margin-left:20px;
}
.QuestionType{
  user-select:none;
  height: 35px;
  width: 75%;
  margin:0 auto 10px auto;
  line-height: 35px;
  cursor:grab;
  position:relative;
  border-radius: 5px;
  background-color: #dde6fa;
  color: #405b96;
}
.QuestionTypeName{
  user-select:none;
  height: 35px;
  width: 36%;
  margin:0 0 10px 37px;
  border: 1px solid #1c3e7f;
  line-height: 35px;
  cursor:grab;

  position:relative;
  float: left;
}
.QuestionTypeID{
  user-select:none;
  height: 35px;
  width: 36%;
  margin:0 0 10px 5px;
  border: 1px solid #1c3e7f;
  line-height: 35px;
  cursor:grab;
  position:relative;
  float: left;
}
.TypeChosen{
  background-color: rgba(28,62,127,0.5);
}
.queMenuItem{
  width: 100%;
  height: 25px;
  font-size:14px;
  text-align: left;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
  line-height: 25px;
  user-select: none;
  opacity: 0.7;
}

/*编辑问卷块的样式*/

/*刚到编辑框中的样式——组件*/
.QuesGhost{
  background-color: #e7edfc;
  width: 100%;
  margin: 0px;
  border: 2px dashed #b4c4ec !important;
}
/*在编辑框中点中的样式——组件+蒙版*/
.QuesChosen{
  opacity: 0.4;
}

.editormainshow{
  width: 700px;
  height: 707px;
  /*background-color:#e6ebef;*/
}
.thepaper{
  margin: 20px 20px 40px 20px;
  background-color: white;
  box-shadow: 0px 1px 2px #a9aaa9;
}
.thePaperTitleAndRemark{
  min-height: 60px;
}
.theQnTitle{
  font-size: 25px;
  line-height: 60px;
}
.thePaperQuestions{
  padding-top:20px ;
}
.thePaperTail{
  margin:30px auto 0px auto;
  padding-bottom: 30px;
}


/*右侧问卷设置、题目编辑窗口*/
.editorright{
  width: 425px;
  height: 707px;
  margin-top: 5px;
  margin-left: 2px;
}
.SetQuestionAndThePaper{
  background-color: white;
  width: 411px;
  height: 664px;
  margin-left: 4px;
  padding-left: 10px;
  padding-right: 10px;
  box-shadow: 0px 1px 2px #a9aaa9
}


/*伪类选择器自定义滚动条样式*/
.scrollbar{
  width: 100%;
  height: 100%;
  overflow-y: scroll;
}
#style-1::-webkit-scrollbar{
  width: 8px;
  background-color: #F5F5F5;
}
#style-12::-webkit-scrollbar{
  width: 8px;
  /*background-color: #F5F5F5;*/
}
#style-1::-webkit-scrollbar-thumb {
  border-radius: 10px;
  background-color:#738cc2;
}
#style-1::-webkit-scrollbar-track {
  -webkit-box-shadow: inset 0 0 6px #e6ebef;
  border-radius: 10px;
  background-color: white;
}


</style>
